﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using SBlogCore.Common.JWTExtend.Schemes;
using System.Text;

namespace SBlogCore.Common.JWTExtend.Extensions
{
    [SkipScan]
    public static class AuthenticationJwtSetup
    {
        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddAuthenticationJwtSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            string secret = AppSetting.ReadAppSettings("Jwt:Secret");
            var keyByteArray = Encoding.ASCII.GetBytes(secret);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            var issuer = AppSetting.ReadAppSettings("Jwt:Issuer");
            var audience = AppSetting.ReadAppSettings("Jwt:Audience");
            //2.1【认证】
            //认证方案：也可以直接写字符串，AddAuthentication("Bearer")
            services.AddAuthentication(x =>
            {
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;//设置默认回退方案
                x.DefaultChallengeScheme = nameof(ApiResponseHandler);//未登录的用户访问需要授权的资源时
                x.DefaultForbidScheme = nameof(ApiResponseHandler);//登陆成功的用户尝试访问未经授权的的资源时
            })
             .AddJwtBearer(o =>
             {
                 o.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuerSigningKey = true,
                     IssuerSigningKey = signingKey,//参数配置在下边
                     ValidateIssuer = true,
                     ValidIssuer = issuer,//发行人
                     ValidateAudience = true,
                     ValidAudience = audience,//订阅人
                     ValidateLifetime = true,
                     ClockSkew = TimeSpan.Zero,//这个是缓冲过期时间，也就是说，即使我们配置了过期时间，这里也要考虑进去，过期时间+缓冲，默认好像是7分钟，你可以直接设置为0
                     RequireExpirationTime = true,
                 };

             })
             //添加默认的方案
             .AddScheme<AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), _ => { }); 

        }
    }
}
